import Vue from 'vue'
import VueRouter from 'vue-router'

import layout from '../views/layout.vue'
import detail from '../views/detail.vue'
import login from '../views/login.vue'
import register from '../views/register.vue'

import article from '../views/article.vue'
import collect from '../views/collect.vue'
import like from '../views/like.vue'
import user from '../views/user.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    component: layout,
    redirect: '/article',
    children: [
      { path: 'article', component: article },
      { path: 'collect', component: collect },
      { path: 'like', component: like },
      { path: 'user', component: user }
    ]
  },
  { path: '/detail', component: detail },
  { path: '/login', component: login },
  { path: '/register', component: register }

]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (to.path === '/login' || to.path === '/register') {
      next()
    } else {
      next('/login')
      Toast('请登录')
    }
  }
})

export default router
